package com.example.utils;

import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

/**
 * @author swain
 * @description:
 * @date 2020/12/2
 */
@Log4j2
public class HttpClientUtils {


    /**
     * 超时毫秒数
     */
    private static final int TIME_OUT = 10 * 1000;

    /**
     * HttpClient 连接池管理类
     */
    private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;

    /**
     * 请求配置
     */
    private static RequestConfig requestConfig;

    static {
        requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(TIME_OUT)
            .setConnectTimeout(TIME_OUT)
            .setSocketTimeout(TIME_OUT).build();

        poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
        /**
         * 整个连接池的最大连接数
         */
        poolingHttpClientConnectionManager.setMaxTotal(50);
        /**
         * 到单个主机的最大连接数
         */
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(10);
    }

    public static CloseableHttpClient getHttpClient() {
        return HttpClients.custom()
            .setConnectionManager(poolingHttpClientConnectionManager)
            .setDefaultRequestConfig(requestConfig)
            .build();
    }

    /**
     * @param url
     * @return java.lang.String
     * @Description 发送get请求
     * @Author swain
     * @Date 2021/1/18
     */
    public static String executeGet(String url) {
        HttpGet get = new HttpGet(url);
        get.setHeader("User-Agent", HeaderUtils.getRandomHeader());
        get.setHeader("referer", url);
        String html = null;
        try (CloseableHttpResponse response = getHttpClient().execute(get)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new Exception("请求失败【" + url + "】");
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                html = EntityUtils.toString(entity, "UTf-8");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return html;
    }


}
